package com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc;

import com.sad.jetpack.v1.datamodel.api.utils.LogcatUtils;

import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class DefaultIPCConnectionProtocolFactory implements IPCConnectionProtocolFactory {
    protected static final String CMD_SOCKET_AVAILABLE_MARK="[SAD-DATA-MODEL-IPC--->-SOCKET-AVAILABLE]";
    protected static final String CMD_SOCKET_GET_HEADER="[SAD-DATA-MODEL-IPC--->-GET-HEADER]";
    protected static final String CMD_SOCKET_READY_TO_CHAT="[SAD-DATA-MODEL-IPC--->-READY_TO_CHAT]";
    protected static final String CMD_SOCKET_ERROR="[SAD-DATA-MODEL-IPC--->-ERROR]";

    private IPCChatMessenger chatMessenger;

    public DefaultIPCConnectionProtocolFactory(IPCChatMessenger chatMessenger) {
        this.chatMessenger = chatMessenger;
    }

    @Override
    public boolean checkSocketAvailability(Socket socket) {
        try {
            InputStream inputStream=socket.getInputStream();
            byte[] kb=CMD_SOCKET_AVAILABLE_MARK.getBytes(StandardCharsets.UTF_8);
            byte[] smb=IPCStreamUtils.readBytes(inputStream,kb.length,kb.length);
            String ph=new String(smb,StandardCharsets.UTF_8);
            LogcatUtils.e("IPC测试-------------->验证客户端连接协议："+ph);
            return CMD_SOCKET_AVAILABLE_MARK.equals(ph);
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    @Override
    public IPCChatHeader getHeader(Socket socket) {
        try {
            byte[] headerBytes=chatMessenger.syncSend(CMD_SOCKET_GET_HEADER.getBytes(StandardCharsets.UTF_8),-1,true);
            if (headerBytes!=null){
                IPCChatHeader ipcChatHeader = IPCChatHeader.parse(headerBytes);
                return ipcChatHeader;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void notifyReadyToChat(Socket socket) {
        try {
            chatMessenger.syncSend(CMD_SOCKET_READY_TO_CHAT.getBytes(StandardCharsets.UTF_8),-1,false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void notifyError(Socket socket, ErrorMessage errorMessage) {
        try {
            //先发标记再发内容
            chatMessenger.syncSend(CMD_SOCKET_ERROR.getBytes(StandardCharsets.UTF_8),-1,false);
            byte[] es=errorMessage.toBytes();
            chatMessenger.syncSend(es,-1,false);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
